<?php
require './Config.php';
require './Answer.php';

class AI{
    private $message;
    private $statistic = array(
        'greetings' => 0,
        'goodbye' => 0,
        'question' => 0,
        'thanks' => 0,
        'contacts' => 0,
        'employees' => 0,
        'info' => 0,
        'price' => 0,
        'profanity' => 0
    );
    
    public function getAnswer($message){
        $this->message = $message;
        $this->prepareMessage();
        $this->countStatistic();
        return $this->prepareAnswer();
    }
    
    private function prepareMessage(){
        $this->message = strtolower($this->message);
        $this->removePolishChar();
        $this-> message = preg_replace('/[^A-Za-z0-9 ]/', '', $this->message); // Removes special chars.
    }
    
    private function countStatistic(){
        $wordArray = explode(' ', $this->message);
        $rules = Config::$rules;
        foreach($wordArray as $word){
            foreach($this->statistic as $stat=>$value){
                if(in_array($word, $rules[$stat])){
                    $this->statistic[$stat]++;
                    break;
                }
            }
        }
    }
    
    private function prepareAnswer(){
        if($this->statistic['profanity'] > 0){
            return Answer::profanity;
        }
        
        if($this->statistic['greetings'] > 0){
            return Answer::greetings;
        }
        
        if($this->statistic['goodbye'] > 0){
            return Answer::goodbye;
        }
        
        if($this->statistic['thanks'] > 0){
            return Answer::thanks;
        }
        
         if($this->statistic['question'] > 0){
            
            if($this->statistic['contacts'] > 0){
                return Answer::questionContacts;
                
            }
            
            if($this->statistic['employees'] > 0){
                return Answer::questionEmployees;
            }
            
            if($this->statistic['info'] > 0){
                return Answer::questionInfo;
            }
            if($this->statistic['price'] > 0){
                return Answer::questionPrice;
            }
             
             
             return Answer::questionDefault;
        }
        
        return 'Nie wiem o co chodzi :(';
    }
    
    private function removePolishChar(){
        $pattern        = array('ą', 'ę', 'ć', 'ł', 'ó', 'ś', 'ż', 'ź');
        $replacement    = array('a', 'e', 'c', 'l', 'o', 's', 'z', 'z');
        
        $this->message = str_replace($pattern, $replacement, $this->message);
        
    }
}
